package cn.suzhang.jsharp.common.config.shiro;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import cn.suzhang.jsharp.module.sys.entity.SysResource;
import cn.suzhang.jsharp.module.sys.service.ResourceService;

/**
 * Shiro配置类
 * 
 * @author suzhang
 * @since 2018-02-11
 */
@Configuration
public class ShiroConfig {
	@Autowired
	private ResourceService resourceService;

	@Bean
	public SecurityManager securityManager(MyRealm myRealm) {
		DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
		manager.setRealm(myRealm);
		return manager;
	}

	@Bean
	public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {

		ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
		shiroFilter.setSecurityManager(securityManager);

		// 设置默认登录URL
		shiroFilter.setLoginUrl("/admin/login");

		// 登录成功后跳转URL
		shiroFilter.setSuccessUrl("/admin/index");

		// 未授权URL
		shiroFilter.setUnauthorizedUrl("/admin/403");

		// 拦截器
		Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
		filterChainDefinitionMap.put("/assets/**", "anon");
		filterChainDefinitionMap.put("/admin/login", "anon");

		List<SysResource> list = resourceService.findAll();
		for (SysResource resource : list) {
			filterChainDefinitionMap.put(resource.getSourceUrl(), "perms[" + resource.getSourceKey() + "]");
		}
		// filterChainDefinitionMap.put("/admin/resource/index",
		// "perms[system:resource:index]");
		// filterChainDefinitionMap.put("/admin/user/index",
		// "perms[system:user:index]");

		 filterChainDefinitionMap.put("/admin/**", "authc");
		shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);
		return shiroFilter;
	}

}
